import cv2 as cv
import numpy as np
from utils.video import GenerateV
from utils.methods import generateImg
import os
import re
import shutil

# 读取模板图片
def osTemplates(path):
  templatesExit = os.path.exists(path)
  if templatesExit == False:
    raise OSError('模板文件夹不存在')
  files = os.listdir(path)
  tData = []
  for i, item in enumerate(files):
    if i+1 >= len(files):
      break
    tem = []
    tem.append(f'{path}/{files[i]}')
    tem.append(f'{path}/{files[i+1]}')
    tData.append(tem)
  return tData  

### 生成视频   path: 图片素材路径
def generateVideo(path, outputPath):
  tData = osTemplates(path)
  gv = GenerateV(outputPath, fps=24, size=(610, 1080))
  animations = [gv.unfoldColumnFromCenter, gv.unfoldRowFromLeft, gv.pieceColumnFromSides, gv.unfoldRowFromRight, gv.unfoldRowFromCenter, gv.unfoldColumnFromBottom, gv.unfoldColumnFromTop]
  for i, item in enumerate(tData):
    num = i % len(animations)
    bg = cv.imread(item[0])
    front = cv.imread(item[1])
    animations[num](bg, front)


# 合成图片并生成视频
def buildVideo(assetsPath, videoPath, filters):
  templatePath = os.path.join(assetsPath, 'templates')
  assetsExit = os.path.exists(assetsPath)
  templateExit = os.path.exists(templatePath)
  if assetsExit == False:
    raise OSError('素材文件夹不存在')
  if templateExit == False:
    os.mkdir(templatePath)
  else:
    shutil.rmtree(templatePath)
    os.mkdir(templatePath)

  files = os.listdir(assetsPath)
  
  for i, item in enumerate(files):
    match = re.search(r'\.(jpg|png|jpeg|gif|webp|svg)', item, re.I)
    if match == False or match == None:
      continue
    template = os.path.join(assetsPath, item)
    img = cv.imread(template)
    resPath = os.path.join(templatePath, f't{i+1}.jpg')
    generateImg(img, outputPath=resPath, filters=filters)

  generateVideo(templatePath, videoPath)  
  shutil.rmtree(templatePath)
